package com.awa.usercenter.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

/**
 * 阿里短信发送工具类
 */
@Slf4j
public class SmsUtil{

    // 产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAI5tKVDXtbCqEYT7vYus2J";
    static final String accessKeySecret = "6uRfwUDCJfRR4XMya0IyfRTvn5bqI2";

    /**
     * 发送短信
     * @param phone 手机号
     * @param smsCode 模版代码
     * @param activeCode 短信6位码
     * @return SendSmsResponse
     * @throws ClientException e
     */
    public static SendSmsResponse sendSms(String phone, String smsCode, String activeCode) throws ClientException {

        //超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:手机号
        request.setPhoneNumbers(phone);
        // 必填:短信签名
        request.setSignName("Vera资源分享小站");
        // 必填:短信模板
        request.setTemplateCode(smsCode);
        // 必填:短信6位码
        request.setTemplateParam("{\"code\":\""+ activeCode + "\"}");

        //此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

}